<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<!-- 3、功能实现: 当发起多个请求时候，只能有一个在进行中的请求，当1个结束后下一个才继续。
function request(url) {
  return new Promise((resolve) => {
    console.log('fetch:', url);
    setTimeout(()=>{resolve(url)}, 1000);
  });
}

function fetchOnlyOne(url) {
  // 待实现    
}

fetchOnlyOne(1);
fetchOnlyOne(2);
fetchOnlyOne(3);
fetchOnlyOne(4);
期待结果输出结果: 1, 2, 3, 4 间隔1s输出。 -->

<body>
  <div>test15-3</div>
  <script>
    function request(url) {
      return new Promise((resolve) => {
        console.log('fetch:', url);
        setTimeout(() => { resolve(url) }, 1000);
      });
    }
    let a 
    let task = []
    function fetchOnlyOne(url) {
       if(a===undefined){
        a = new req()
       }
        a.execute(url)
    }
    function req(url) {
      setTimeout(() => {
        this.next()
      }, 0);
    }
    req.prototype.execute=function(url){
      let fn = ()=>{
        request(url).then(()=>{
          this.next()
        })
      }
      task.push(fn)

    }
    req.prototype.next= function (url){
      let fn = task.shift()
      fn&&fn()
    }
    fetchOnlyOne(1);
    fetchOnlyOne(2);
    fetchOnlyOne(3);
    fetchOnlyOne(4);
        // 期待结果输出结果: 1, 2, 3, 4 间隔1s输出。
  </script>
</body>

</html>